package com.example.chatapp.service;

import com.example.chatapp.common.BusinessException;
import com.example.chatapp.model.Friendship;
import com.example.chatapp.model.User;
import com.example.chatapp.repository.FriendshipRepository;
import com.example.chatapp.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FriendshipService {
    
    private final FriendshipRepository friendshipRepository;
    private final UserRepository userRepository;
    
    public FriendshipService(FriendshipRepository friendshipRepository, UserRepository userRepository) {
        this.friendshipRepository = friendshipRepository;
        this.userRepository = userRepository;
    }
    
    /**
     * 添加好友（双向关系）
     */
    @Transactional
    public void addFriend(Long userId, String friendUsername) {
        // 查找好友用户
        User friend = userRepository.findByUsername(friendUsername)
                .orElseThrow(() -> new BusinessException(404, "用户不存在"));
        
        Long friendId = friend.getId();
        
        // 不能添加自己为好友
        if (userId.equals(friendId)) {
            throw new BusinessException(400, "不能添加自己为好友");
        }
        
        // 检查是否已经是好友
        if (friendshipRepository.existsByUserIdAndFriendId(userId, friendId)) {
            throw new BusinessException(400, "已经是好友关系");
        }
        
        // 创建双向好友关系
        Friendship friendship1 = new Friendship();
        friendship1.setUserId(userId);
        friendship1.setFriendId(friendId);
        friendship1.setCreatedAt(LocalDateTime.now());
        
        Friendship friendship2 = new Friendship();
        friendship2.setUserId(friendId);
        friendship2.setFriendId(userId);
        friendship2.setCreatedAt(LocalDateTime.now());
        
        friendshipRepository.save(friendship1);
        friendshipRepository.save(friendship2);
    }
    
    /**
     * 删除好友（双向删除）
     */
    @Transactional
    public void removeFriend(Long userId, String friendUsername) {
        // 查找好友用户
        User friend = userRepository.findByUsername(friendUsername)
                .orElseThrow(() -> new BusinessException(404, "用户不存在"));
        
        Long friendId = friend.getId();
        
        // 检查是否是好友关系
        if (!friendshipRepository.existsByUserIdAndFriendId(userId, friendId)) {
            throw new BusinessException(400, "不是好友关系");
        }
        
        // 删除双向好友关系
        friendshipRepository.deleteByUserIdAndFriendId(userId, friendId);
        friendshipRepository.deleteByUserIdAndFriendId(friendId, userId);
    }
    
    /**
     * 获取好友列表
     */
    public List<User> getFriendList(Long userId) {
        List<Long> friendIds = friendshipRepository.findFriendIdsByUserId(userId);
        
        if (friendIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        return userRepository.findAllById(friendIds);
    }
    
    /**
     * 获取好友用户名列表
     */
    public List<String> getFriendUsernameList(Long userId) {
        return getFriendList(userId).stream()
                .map(User::getUsername)
                .collect(Collectors.toList());
    }
    
    /**
     * 检查是否是好友
     */
    public boolean isFriend(Long userId, String friendUsername) {
        User friend = userRepository.findByUsername(friendUsername).orElse(null);
        if (friend == null) {
            return false;
        }
        return friendshipRepository.existsByUserIdAndFriendId(userId, friend.getId());
    }
    
    /**
     * 获取好友数量
     */
    public long getFriendCount(Long userId) {
        return friendshipRepository.countByUserId(userId);
    }
}
